<template lang="html">
  <div v-if="indexShow">
    <h1>我是首页</h1>
    <div class="btn-group">
      <button size="mini" @click="reqSkuNames">原生request获取数据</button>
      <button size="mini" @click="getSkuNames">封装request获取数据</button>
    </div>
    <div>
      商品数量: {{totalCount}}
    </div>
  </div>
</template>

<script>
// import {getCurrentPageUrl} from '@/utils/'
import {$ajax} from '@/utils/request.js'
import {getUserInfo, toast, alert, navigateTo, setStorage} from '@/utils/wxapi.js'
export default {
  name: 'Index',
  data () {
    return {
      totalCount: 0,
      indexShow: false
    }
  },
  created () {},
  mounted () {
    // 获取当前页面url
    console.log(this.$root.$mp)
    // 检查是否获取授权
    getUserInfo().then(res => {
      // 已经授权，获取用户信息
      this.indexShow = true
      console.log('用户数据', res)
      toast('获取用户数据成功')
      setStorage('token', res.signature)
    }).catch(e => {
      // 未授权，跳转授权页面
      alert('尚未进行授权，请点击确定跳转到授权页面进行授权。').then(res => {
        navigateTo('/pages/author/main')
      })
    })
  },
  methods: {
    // 原生request
    reqSkuNames () {
      console.log('开始请求数据')
      // 打开loading
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      // 请求数据
      wx.request({
        url: 'http://beta.jxc4.com/v2/sku/GetSkuNames',
        data: {
          keyword: '',
          pageSize: 5
        },
        header: {
          token: '12312312'
        },
        method: 'GET',
        dataType: 'json',
        success: res => {
          console.log('获取数据成功')
          wx.showToast({
            title: '获取成功',
            icon: 'none'
          })
          console.log(res)
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            title: '获取失败',
            icon: 'none'
          })
        },
        complete: () => {
          setTimeout(() => {
            wx.hideLoading()
          }, 1000)
        }
      })
    },
    // 封装request
    getSkuNames () {
      $ajax({
        url: '/v2/sku/GetSkuNames',
        // methods: 'GET',
        data: {
          keyword: '',
          pageSize: -1
        }
      }).then(res => {
        wx.showToast({
          title: '获取成功',
          icon: 'none'
        })
        console.log(JSON.parse(res.data))
        let data = JSON.parse(res.data)
        this.totalCount = data.totalCount
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss">
.btn-group {
  margin-top: 20px;
}
</style>
